//
//  ZDEmojiViewController.swift
//  ZDEmojiKeyBoard
//
//  Created by Apple on 15/11/4.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class ZDEmojiViewController: UIViewController {
    
    //cell重用标识
    private let cellReuseIdentifier = "emojiCell"
    
    //保存选中的按钮
    private var selectedBtn: UIButton?

    override func viewDidLoad() {
        super.viewDidLoad()

//        view.backgroundColor = UIColor.redColor()
        
        prepareUI()
        
        setCollectionView()
        
        setToolBar()
        
    }
    
    
    //MARK: - 准备UI
    private func prepareUI() {
    
        //添加子控件
        view.addSubview(toolBar)
        view.addSubview(collectionView)

        
        //添加约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false

        //为collectView添加水平约束
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
        
        //为toolbar添加水平约束
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : toolBar]))
        
        //添加垂直约束
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView, "tb" : toolBar]))
    }
    
    
    //MARK: - setCollectionView
    private func setCollectionView() {
        
        //设置背景颜色
        collectionView.backgroundColor = UIColor(white: 0.85, alpha: 1.0)
        
        //指定数据源 和 代理
        collectionView.dataSource = self
        collectionView.delegate = self
    
        collectionView.registerClass(ZDCollectionViewCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)
    }
    
    
    //设置按钮index参考点  ———— 因为在toolBar中通过tag取控件时，如果tag=0 取到的不是button 而是toolBar
    private let baseIndex = 1000
    
    //MARK: - 设置toolBar
    private func setToolBar() {
        
        var items = [UIBarButtonItem]()
        
        guard let packages = emojiPackages else {
        
            return
        }
        
        var index = 0
        
        for emojiPackage in packages {
            
            let title = emojiPackage.group_name_cn
            
            let btn = UIButton()
            
            btn.tag = index + baseIndex
            
            //默认选中第一个按钮
            if index == 0 {
            
                switchBtn(btn)
            }
            
            btn.setTitle(title, forState: UIControlState.Normal)
            btn.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Selected)
            
            btn.addTarget(self, action: "btnClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //必须sizeToFit  否则看不到  默认fontSize是18
            btn.sizeToFit()
            
            let item = UIBarButtonItem(customView: btn)
            
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            index++
        }
        
        //移除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    }

    
    ///MARK: - toolbar按钮点击事件
    @objc private func btnClick(btn: UIButton) {
    
        //修改按钮的选中状态
        switchBtn(btn)
        
        //collectionView显示对应section
        let indexPath = NSIndexPath(forItem: 0, inSection: btn.tag - baseIndex)
        collectionView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.Left)
    }
    
    ///修改按钮的选中状态
    private func switchBtn(btn: UIButton) {
    
        selectedBtn?.selected = false
        btn.selected = true
        selectedBtn = btn
    }
    
//    //MARK: - 设置toolBar
//    private func setToolBar() {
//    
//        let itemSettings = [
//            ["title": "最近", "action": "recent"],
//            ["title": "默认", "action": "defaulting"],
//            ["title": "Emoji", "action": "emoji"],
//            ["title": "浪小花", "action": "sina"]]
//        
//        var items = [UIBarButtonItem]()
//        
//        for dict in itemSettings {
//        
//            let title = dict["title"]
//            let action = dict["action"]!
//            
//            let btn = UIButton()
//            
//            btn.setTitle(title, forState: UIControlState.Normal)
//            btn.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
//            btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Selected)
//            
//            btn.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
//            
////            btn.titleLabel?.font = UIFont.systemFontOfSize(15)
//            
//            //必须sizeToFit  否则看不到  默认fontSize是18
//            btn.sizeToFit()
//        
//            let item = UIBarButtonItem(customView: btn)
//            
//            items.append(item)
//            
//            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
//        }
//        
//        //移除最后一个弹簧
//        items.removeLast()
//        
//        toolBar.items = items
//    }
    
    
//    //MARK: - barButton点击事件
//    @objc private func recent() {
//    
//        print(__FUNCTION__)
//    }
//    
//    @objc private func defaulting() {
//        
//        print(__FUNCTION__)
//    }
//    
//    @objc private func emoji() {
//        
//        print(__FUNCTION__)
//    }
//    
//    @objc private func sina() {
//        
//        print(__FUNCTION__)
//    }
    
    
    ///记录当前表情键盘输入的textView
    weak var textView: UITextView?
    
//    ///插入emoji表情
//    private func insertEmoji(emoji: ZDEmoji) {
//        
//        //判断textView是否有值
//        guard let textView = self.textView else {
//        
//            return
//        }
//    
//        //如果选中的是默认emoji表情(本质上就是字符串)，可以直接插入
//        if let text = emoji.emojiString {
//        
//            textView.insertText(text)
//            
//            return
//        }
//        
//        //如果选中的是图片表情
//        guard let imagePath = emoji.pngPath else {
//        
//            return
//        }
//    
//        
//        //取出表情图片
//        let image = UIImage(contentsOfFile: imagePath)
//        
//        //创建附件
//        let attachment = ZDTextAttachment()
//        //保存图片对应的字段
//        attachment.name = emoji.chs
//        
//        //设置附件的图片为表情图片
//        attachment.image = image;
//        
//        //获取线高
//        let height = textView.font?.lineHeight ?? 10
//        
//        //设置附件图片的大小
//        attachment.bounds = CGRect(x: 0, y: -height * 0.25, width: height, height: height)
//        
//        //创建带附件的属性文本
//        let attributeStr = NSAttributedString(attachment: attachment)
//        
//        //获取textView的现有属性文本 转换为可变的属性文本
//        let attributeStrM = NSMutableAttributedString(attributedString: textView.attributedText)
//        
//        //获取textView当前选中文本的范围
//        let range = textView.selectedRange
//        
//        //将选中的文本替换为带有表情图片的属性文本
//        attributeStrM.replaceCharactersInRange(range, withAttributedString: attributeStr)
//        
//        //设置新替换的表情属性文本的字体 ———— 解决重复输入表情图片时，后面的表情图片变小的bug(后面输入的属性文本font参考其前一个属性文本，如果没有设置就是默认值)
//        attributeStrM.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(range.location, 1))
//        
//        //将最终的属性文本重新设置给textView的属性文本
//        textView.attributedText = attributeStrM
//        
//        //重新定位光标的位置 否则设置完属性文本后 光标自动跑到最后
//        textView.selectedRange = NSMakeRange(range.location+attributeStr.length, 0)
//        
//    }
    
    deinit
    {
        print("表情控制器挂了")
    }
    
    //MARK: - 懒加载collectionView
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: ZDCollectionViewFlowLayout())
    
    //MARK: - 懒加载toolbar
    private lazy var toolBar: UIToolbar = {
    
        let toolBar = UIToolbar()
        
        toolBar.barTintColor = UIColor(white: 0.85, alpha: 1.0)
        
        return toolBar
    }()
    
    //懒加载模型
    private lazy var emojiPackages: [ZDEmojiPackage]? = {
    
        let packages = ZDEmojiPackage.emojiPackages
        
//        print(packages)
        
        return packages
    }()
}


//在当前类的扩展中 实现代理方法
extension ZDEmojiViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return emojiPackages?.count ?? 0
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let emojiPackage = emojiPackages![section]
        
        return emojiPackage.emoticons?.count ?? 0
    }

    /*  在滚动scrollView时 只会调用该方法 而不会再调用上面两个数据源方法  */
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as! ZDCollectionViewCell
        
//        cell.backgroundColor = UIColor(red: CGFloat(arc4random_uniform(256)) / 255.0, green: CGFloat(arc4random_uniform(256)) / 255.0, blue: CGFloat(arc4random_uniform(256)) / 255.0, alpha: 1.0)
        
        let emojiPackage = emojiPackages![indexPath.section]
        
        cell.emoji = emojiPackage.emoticons![indexPath.item]
        
        return cell
    }
    
    ///scrollView滚动停下来时调用
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        //获取当前显示的item的indexPath
        let indexPath = collectionView.indexPathsForVisibleItems().first!
        
//        print(toolBar.subviews)
        
        let button = toolBar.viewWithTag(indexPath.section + baseIndex) as! UIButton
        
        //切换按钮
        switchBtn(button)
    }
    
    ///选中某个cell时调用
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let emoji = emojiPackages![indexPath.section].emoticons![indexPath.item]
        
//        print(emoji)
        
        //插入emoji表情
        textView?.insertEmoji(emoji)
        
        //如果点击的是最近表情包 就不更新到"最近"表情包
        if indexPath.section == 0 {
        
            return
        }
        
        //添加选中的表情到"最近"表情包
        ZDEmojiPackage.updateRecentWithEmoji(emoji)
    }

}

//MARK: - 自定义流水布局类
class ZDCollectionViewFlowLayout: UICollectionViewFlowLayout {

    //重写父类的prepareLayout 设置layout相关属性 在该方法中可以拿到collectionView的准确frame
    //当然在viewDidAppear方法中也可以拿到collectionView的准确frame；在viewDidLoad、viewWillAppear方法中拿不到collectionView的准确frame
    override func prepareLayout() {
        
        //一定要先调用父类的方法
        super.prepareLayout()
        
//        print("collectionView:\(collectionView)")
        
        let width = collectionView!.bounds.width / 7.0
        let height = collectionView!.bounds.height / 3.0
        
        itemSize = CGSize(width: width, height: height)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        
        //设置滚动方向 ———— 水平滚动
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        //设置分页
        collectionView?.pagingEnabled = true
        
        //隐藏水平滚动条
        collectionView?.showsHorizontalScrollIndicator = false
    }
}

//MARK: - 自定义collectionCell
class ZDCollectionViewCell: UICollectionViewCell {
    
    var emoji: ZDEmoji? {
    
        didSet {
            
//            if (emoji?.removeBtn)! {
//            
//                emojiBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
//                emojiBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
//                
//                return
//            }
            
//            emojiBtn.setImage(nil, forState: UIControlState.Normal)
//            emojiBtn.setImage(nil, forState: UIControlState.Highlighted)
        
            if let pngPath = emoji?.pngPath {
            
                emojiBtn.setImage(UIImage(contentsOfFile: pngPath), forState: UIControlState.Normal)
            }
            else {
            
                emojiBtn.setImage(nil, forState: UIControlState.Normal)
            }
            
            emojiBtn.setTitle(emoji?.emojiString, forState: UIControlState.Normal)
            
            if (emoji?.removeBtn)! {
                
                emojiBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    
    //MARK: - 构造方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    //MARK: - 准备UI
    private func prepareUI() {
    
        //添加子控件
        contentView.addSubview(emojiBtn)
        
//        print("frame:\(frame)")
        
        //设置frame  每一边都内插5个点
//        emojiBtn.frame = CGRectInset(frame, 5, 5)  //不能传frame  因为frame是参考父控件左上角的
        emojiBtn.frame = CGRectInset(bounds, 5, 5)
    }
    
    
    //MARK: - 懒加载button
    private lazy var emojiBtn: UIButton = {
    
        let btn = UIButton()
        
//        btn.backgroundColor = UIColor.blackColor()
        btn.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        //禁止按钮与用户交互 否则会拦截collectionViewCell的选中响应事件
        btn.userInteractionEnabled = false
        
        return btn
    }()
    
}